<template>
    <!-- pages/buymealdetails/pay/index.wxml -->
    <view class="page">
        <!-- <view class="meal mt-20 flexbox-sb">
    <view>
      <view class="mealtext1">
        {{mealList.type < 2 ? "单项套餐" : "多项套餐"}}
        <text>{{mealList.times}}次</text>
      </view>
      <view class="mealtext2 mt-10">{{mealList.categoryname}}</view>
    </view>
    <view class="mt-16">
      <text class="mealtext3">¥</text>
      <text class="mealtext4">{{mealList.price}}</text>
    </view>
  </view> -->
        <view class="puy mt-20">
            <view class="text-red">¥{{ mealObj.price }}</view>
            <view class="time centers" v-if="time > 0">
                剩余支付时间
                <van-count-down :time="time" format="mm 分 ss 秒" />
            </view>
            <view class="title">选择支付方式</view>
            <view class="flexbox-sb puybox" :data-index="index" @tap="onClick" v-for="(item, index) in list" :key="index">
                <view :class="(listindex === index ? 'puytext2' : 'puytext1') + ' centers'">
                    <image class="icon-32 mr-20" :src="imgUrl + item.img"></image>
                    <text>{{ item.title }}</text>
                    <text v-if="index === 1">(￥{{ wallet }})</text>
                </view>

                <view v-if="listindex === index" class="bigbox">
                    <view class="smbox"></view>
                </view>
            </view>
            <view class="btn" @tap="onPayment">确定</view>
        </view>

        <van-overlay :show="showpay" @tap.native="onClickHide">
            <view class="overlaybox" @tap.stop.prevent="shop">
                <view class="pab"><van-icon @click="onClickHide" size="20px" name="cross" /></view>
                <view class="tit">请输入密码</view>
                <view class="tit1">支付金额</view>
                <view class="tit2">¥{{ mealObj.price }}</view>
                <view class="hrs"></view>
                <view class="flexbox-sb centers p-20">
                    <text>余额</text>
                    <text class="t-c">￥{{ wallet }}</text>
                </view>
                <padinput id="padinput" :Value="value" @infotan="getpassword($event, { tagId: 'padinput' })" :bool="true" :isFocus="isFocus"></padinput>
                <!-- <view class="overlaybox2" catchtap="onClickHide">取消</view> -->
            </view>
        </van-overlay>
    </view>
</template>

<script>
// pages/payment/index.js
const app = getApp(); // 引入app

import _request from '../../../utils/request.js';
import { getTime, getTouchData, toDecimal2 } from '../../../utils/util.js';
let isPaying = false;
export default {
    data() {
        return {
            list: [
                {
                    title: '微信支付',
                    img: '/static/pages/buymealdetails/pay/wxpay.png'
                },
                {
                    title: '余额支付',
                    img: '/static/pages/buymealdetails/pay/yepay.png'
                }
            ],

            listindex: -1,
            imgUrl: app.globalData.imgUrl,

            //全局img路径
            wallet: 0,

            mealObj: null,
            password: '',
            showpay: false,
            bool: false,
            isFocus: false,
            value: '',
            time: 0
        };
    }
    /**
     * 生命周期函数--监听页面加载
     */,
    onLoad: function (options) {
        let data = JSON.parse(decodeURIComponent(options.data));
        data.price = toDecimal2(data.price);
        this.setData({
            mealObj: data
        });
        this.getCashInfo();
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        // _request.get('/settings/initPayWord', {
        //   userId: wx.getStorageSync('userid'),
        // }).then((res) => {
        //   if (res.data.message == '支付密码还未设置' && res.data.data == 0) {
        //     wx.showModal({
        //       title: '您还未设置密码',
        //       content: '请先设置密码',
        //       confirmText: '前往设置',
        //       success(res) {
        //         if (res.confirm) {
        //           wx.navigateTo({
        //             url: '/pages/setpaypassword/index',
        //           })
        //         } else if (res.cancel) {}
        //       }
        //     })
        //   }
        // })
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {},
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {},
    methods: {
        // 点击事件
        onClick(e) {
            const { index } = e.currentTarget.dataset;
            this.setData({
                listindex: index,
                bool: true,
                value: ''
            });
        },

        // 获取密码
        getpassword(e, _dataset) {
            /* ---处理dataset begin--- */
            this.datasetHandle(e, _dataset);
            /* ---处理dataset end--- */
            this.setData({
                password: e.detail.inputValue
            });

            if (this.password.length == 6) {
                _request
                    .get('/settings/initPayWord', {
                        userId: uni.getStorageSync('userid')
                    })
                    .then((res) => {
                        if (res.data.message == '支付密码还未设置' && res.data.data == 0) {
                            this.setData({
                                showpay: false,
                                value: ''
                            });
                            this.setData({
                                password: ''
                            });
                            uni.showModal({
                                title: '您还未设置密码',
                                content: '请先设置密码',
                                confirmText: '前往设置',

                                success(res) {
                                    if (res.confirm) {
                                        uni.navigateTo({
                                            url: '/pages/setpaypassword/index'
                                        });
                                    } else if (res.cancel) {
                                    }
                                }
                            });
                        } else if (res.data.message == '支付密码已设置' && res.data.data == 1) {
                            _request
                                .postObj('/settings/checkPayWord', {
                                    payWord: this.password,
                                    userId: uni.getStorageSync('userid')
                                })
                                .then((res) => {
                                    if (res.data.code === 200) {
                                        this.walletPayment();
                                    }
                                });
                        }
                    });
            }
        },

        // 取消支付
        onClickHide() {
            this.setData({
                showpay: false,
                value: ''
            });
        },

        // 支付
        onPayment() {
            if (!this.bool) {
                uni.showToast({
                    title: '请选择支付方式',
                    icon: 'none',
                    duration: 2000
                });
            } else if (this.bool && this.listindex == 1) {
                _request
                    .get('/settings/initPayWord', {
                        userId: uni.getStorageSync('userid')
                    })
                    .then((res) => {
                        if (res.data.message == '支付密码还未设置' && res.data.data == 0) {
                            uni.showModal({
                                title: '您还未设置密码',
                                content: '请先设置密码',
                                confirmText: '前往设置',

                                success(res) {
                                    if (res.confirm) {
                                        uni.navigateTo({
                                            url: '/pages/setpaypassword/index'
                                        });
                                    } else if (res.cancel) {
                                    }
                                }
                            });
                        } else {
                            this.setData({
                                showpay: true,
                                isFocus: true
                            });
                        }
                    });
            } else if (this.bool && this.listindex == 0) {
                // 微信支付, 防止重复支付
                if (isPaying) {
                    return;
                }

                isPaying = true;
                uni.login({
                    success: (res) => {
                        this.wxPayment(res.code);
                    }
                });
            }
        },

        // wx支付
        wxPayment(code) {
            let vm = this;

            _request
                .postObj(
                    '/packagePay/wxAppletpay',
                    {
                        serviceId: this.mealObj.serviceId,
                        money: this.mealObj.price,
                        packageId: this.mealObj.packageId,
                        code,
                        userId: uni.getStorageSync('userid')
                    },
                    app.globalData.userType
                )
                .then((res) => {
                    if (res.data.code == 200) {
                        let data = {
                            timeStamp: res.data.data.timestamp,
                            nonceStr: res.data.data.nonceStr,
                            package: res.data.data.pkg,
                            signType: 'MD5',
                            paySign: res.data.data.sign
                        };
                        uni.requestPayment({
                            ...data,

                            success(res) {
                                uni.showToast({
                                    title: '支付成功',
                                    icon: 'none',
                                    duration: 2000
                                });
                                setTimeout(() => {
                                    uni.navigateTo({
                                        url: '/pages/mypreferentialcard/index'
                                    });
                                }, 1000);
                            },

                            fail(res) {
                                uni.showToast({
                                    title: '支付失败!',
                                    icon: 'none'
                                });
                            },

                            complete(res) {
                                isPaying = false;
                            }
                        });
                    } else {
                        isPaying = false;
                    }
                })
                .catch((error) => {});
        },

        // 钱包支付 支付类型，1订单支付，2，订单加价
        walletPayment() {
            _request
                .postObj('/packagePay/yiyuePackagePay', {
                    serviceId: this.mealObj.serviceId,
                    money: this.mealObj.price,
                    packageId: this.mealObj.packageId,
                    userId: uni.getStorageSync('userid')
                })
                .then((res) => {
                    if (res.data.code == 200) {
                        uni.showToast({
                            title: '支付成功',
                            icon: 'none',
                            duration: 2000
                        });
                        this.setData({
                            showpay: false,
                            password: ''
                        });
                        setTimeout(() => {
                            uni.navigateTo({
                                url: '/pages/mypreferentialcard/index'
                            });
                        }, 1000);
                    }
                })
                .catch((error) => {});
        },

        // 获取账号余额
        getCashInfo() {
            _request
                .get('/wallet/getCashInfo', {
                    id: uni.getStorageSync('userid'),
                    userId: uni.getStorageSync('userid')
                })
                .then((res) => {
                    this.setData({
                        wallet: res.data.data.realBalance
                    });
                })
                .catch((error) => {
                    console.log(error, 'error');
                });
        },

        shop() {
            console.log('占位：函数 shop 未声明');
        }
    }
};
</script>
<style>
/* pages/buymealdetails/pay/index.wxss */
.page {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
}

/* 支付方式 */
.puy {
    width: 710rpx;
    background: #ffffff;
    box-shadow: 1px 1px 4px 1px rgba(241, 241, 241, 0.4);
    border-radius: 5px;
    padding: 40rpx 20rpx 80rpx 20rpx;
    box-sizing: border-box;
}

.title {
    margin-top: 50rpx;
    text-align: center;
}

.text-red {
    width: 100%;
    text-align: center;
    height: 66rpx;
    font-size: 48rpx;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #ff1b0b;
    line-height: 66rpx;
}

.time {
    font-size: 28rpx;
    font-family: PingFang-SC-Medium, PingFang-SC;
    font-weight: 500;
    color: #333333;
    justify-content: center;
    margin: 20rpx 0 80rpx 0;
}

.van-count-down {
    font-size: 28rpx !important;
    font-family: PingFangSC-Regular, PingFang SC !important;
    font-weight: 500 !important;
    color: #333333 !important;
}

.hrs {
    margin: 10rpx 0 20rpx 0;
}

.bigbox {
    width: 30rpx;
    height: 30rpx;
    border: 1px solid #ff8722;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
}

.smbox {
    width: 18rpx;
    height: 18rpx;
    border-radius: 50%;
    background: #ff8722;
}

.puytext1 {
    height: 40rpx;
    font-size: 28rpx;
    font-family: PingFang-SC-Medium, PingFang-SC;
    font-weight: 500;
    color: #666666;
    line-height: 40rpx;
}

.puytext2 {
    height: 40rpx;
    font-size: 28rpx;
    font-family: PingFang-SC-Medium, PingFang-SC;
    font-weight: 500;
    color: #ff8722 !important;
    line-height: 40rpx;
}

.puybox {
    padding: 10rpx 0;
    margin: 10rpx 0;
    box-sizing: border-box;
}

/* 按钮 */
.btn {
    width: 670rpx;
    height: 84rpx;
    background: #ff8722;
    border-radius: 21px;
    font-size: 32rpx;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #ffffff;
    line-height: 84rpx;
    text-align: center;
    margin-top: 50rpx;
}

.overlaybox {
    position: absolute;
    bottom: 0rpx;
    background: #ffffff;
    padding: 40rpx 20rpx;
    width: 650rpx;
    top: 20%;
    height: 460rpx;
    margin: 0 auto;
    left: 0;
    box-sizing: border-box;
    right: 0;
    border-radius: 10rpx;
}

.tit {
    width: 100%;
    text-align: center;
    margin-bottom: 40rpx;
}

.tit1 {
    width: 100%;
    text-align: center;
    font-size: 20rpx;
}

.tit2 {
    width: 100%;
    text-align: center;
    font-size: 40rpx;
    margin-bottom: 40rpx;
}

.p-20 {
    padding: 0 20rpx;
    margin-bottom: 30rpx;
}

.pab {
    position: absolute;
}

.t-c {
    color: #ff8722;
}

.overlaybox2 {
    width: 710rpx;
    height: 100rpx;
    background: #ff8722;
    line-height: 100rpx;
    text-align: center;
    line-height: 100rpx;
    margin-top: 30rpx;
    border-radius: 80rpx;
    color: #ffffff;
}
</style>
